<template>
    <section>
        <main class="bglight">
            <header class="live-header">
                <div>
                    <router-link to="/" slot="left">
                        <span class="back fs20 ml10 iconfont icon-fanhuizuo" ></span>
                    </router-link>
                    <span @click="showNav=!showNav">
                        <span class="fs14">直播 节目单</span>
                        <em class="iconfont icon-zhankaixia fs10"></em>
                    </span>
                    <router-link to="/trade" slot="left">
                        <span class="mr10 yellow">交易</span>
                    </router-link>
                </div>
            </header>
            <transition name="slide-fade">
                <div class="list bggray pb20" v-show="showNav">
                    <div
                        class="clearfix fs14 fontc2"
                        :key="idx"
                        v-for="(item,idx) in liveMessage.program">
                        <img class="fl mt10 ml20" :src="item.pictureUrl" width="40" height="40" alt="">
                        <section class="ml20">
                            <h6 class="tl lh30 mt5">{{item.teacherName}}</h6>
                            <p class="tl lh20 fs12 fontc3">直播时间：{{item.liveTime}}(工作日)</p>
                        </section>
                    </div>
                </div>
            </transition>
            <div class="mt40">
                <section class="pl10 pr10 bgwhite">
                    <div
                        class="video"
                        @click="videoTip"
                        style="height: 1.5rem;background: url('./static/imgs/live.png');">
                        <section class="teacher-msg clearfix" v-show="showTeacherTip">
                            <img class="fl ml20" width="40" height="40" :src="liveMessage.teacher?liveMessage.teacher.pictureUrl:null" alt="">
                            <div class="fl ml20 fs14 white">
                                <h3 class="lh30 tl">{{curTeacherMsg.name}}</h3>
                                <p class="lh30 tl">{{curTeacherMsg.msg}}</p>
                                <p class="fr lh30" @click.stop="showTeacherTip=false">关闭指令</p>
                            </div>
                        </section>
                    </div>
                </section>
                <div class="nav lh40 fs14 flex pt5 mb5 bgwhite">
                    <span
                        class="lh35 tc"
                        @click="active='tab-container1'"
                        :class="{red:active=='tab-container1',fontc1:active=='tab-container2'}">
                            <i class="lh35 dbi">直播互动</i>
                        </span>
                    <span
                        class="lh35"
                        @click="active='tab-container2'"
                        :class="{red:active=='tab-container2',fontc1:active=='tab-container1'}">
                            <i class="lh35 dbi">老师指导</i>
                        </span>
                </div>
                <div class="content pl20 pr20 bglight bgwhite">
                    <section style="width: 100%;" v-show="active=='tab-container1'">
                        <mt-loadmore
                            :top-method="getMoreMsg"
                            ref="loadmore"
                            @top-status-change="handleTopChange">
                            <section class="box-wrap" ref="query-msg-wrap">
                                <div
                                    class="tl mt10 box"
                                    style="width: 100%;"
                                    v-for="(item,idx) in queryPaging"
                                    :key="idx">
                                        <p
                                            class="lh20 blue"
                                            :class="{tl:item.chatType==1,tr:item.chatType==2}">{{item.name}} {{item.updateTime|formatTime}}</p>
                                        <p
                                            class="lh20 fontc1 ml20 mr20"
                                            :class="{'teacher':item.chatType==1,'user':item.chatType==2}">{{item.msg}}
                                            <span style="background: url('./static/imgs/bubble.svg')"></span>
                                            <em style="background: url('./static/imgs/bubblew.svg')"></em>
                                        </p>
                                </div>
                            </section>
                            <p class="lh50 fontc4" v-show="queryPaging.length<=0">暂无直播互动消息</p>
                        </mt-loadmore>
                    </section>
                    <section class="teacher-msg" v-show="active=='tab-container2'">
                        <section class="box-wrap">
                            <div
                                class="tl mt10 box"
                                style="width: 100%;"
                                v-for="(item,idx) in teacherMsg"
                                :key="idx">
                                    <p
                                        class="lh20 fontc3"
                                        :class="{tl:item.chatType==1,tr:item.chatType==2}">{{item.name}} {{item.updateTime|formatTime}}</p>
                                    <p
                                        class="lh20 fontc1 ml20 mr20"
                                        :class="{'teacher':item.chatType==1,'user':item.chatType==2}">{{item.msg}}
                                        <span style="background: url('./static/imgs/bubble.svg')"></span>
                                        <em style="background: url('./static/imgs/bubblew.svg')"></em>
                                    </p>
                            </div>
                        </section>
                        <p class="lh50 fontc4" v-show="teacherMsg.length<=0">暂无老师直播消息</p>
                    </section>
                </div>
                <div class="text-wrap">
                    <input
                        type="text"
                        class="fs14"
                        v-model="text"
                        :placeholder="withTeacherLive?'请输入回复信息':'没有老师直播，不可发言'">
                    <!-- <mt-button size="small" class="mr20" :type="withTeacherLive?'primary':'default'" @click="sendMsg">发送</mt-button> -->
                    <span class="mr20 mt10 fs14 lh40 blue" @click="sendMsg">发送</span>
                </div>
            </div>
        </main>
    </section>
</template>

<script>
import { MessageBox, Toast, Indicator, TabContainer, TabContainerItem, Button,Loadmore} from 'mint-ui'
import Vue from 'vue';

Vue.component(TabContainer);
Vue.component(TabContainerItem);
Vue.component(Button);
Vue.component(Loadmore);

import axios   from 'axios'
import { mapState } from 'vuex'
export default {
    name : "Live",
    data () {
        return {
            active: "tab-container1",
            showNav: false,
            topStatus: "",
            liveMessage : {},
            teacherMsg: [],
            queryPaging : [],
            queryPage: 0,
            teacherpage: 0,
            showTeacherTip: false,
            curTeacherMsg: {},
            text: "",
            ws: null,
            token1: null,
            token2: null,
            withTeacherLive: false,
        }
    },
    created () {
        this.getToken();
        // 直播相关信息
        this.getLiveMessage();
        // 直播互动
        this.queryPagingBy();
    },
    computed: {
        ...mapState(['userInfo'])
    },
    methods : {
        getToken () {
            const getCookie = (name) => { 
                var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); 
                　　 return (arr=document.cookie.match(reg))?unescape(arr[2]):null;
            };
            this.token1 = getCookie('token1');
            this.token2 = getCookie('token2');
        },
        handleTopChange(status) {
            this.topStatus = status;
        },
        getMoreMsg () {
            this.queryPagingBy();
        },
        getLiveMessage () {
            Indicator.open('加载直播信息');
			axios({
				methods: "get",
                url: '/user/live/getLiveMessage.do',
			})
			.then((res) => {
				Indicator.close();
				res = res.data;
                if (res.code != 200) {
                    Toast('请求直播信息出错')
                    return;
                };

                this.liveMessage = res.data;
                if (res.data.stopLive) {// 非直播时间
                    MessageBox('直播','非直播时间');
                } else {
                    // 直播时间
                    if (res.data.teacher) { // 有直播老师
                        this.withTeacherLive = true;
                        // 请求老师的历史消息
                        this.findTeacherMsg();
                        // ws 连接
                        this.getChatting();
                    } else {//没有直播老师
                        MessageBox('直播','没有直播老师');
                    }
                }
			})
        },
        findTeacherMsg () {
            Indicator.open('加载直播信息');
			axios({
				methods: "get",
				url: '/user/live/findTeacherMsg.do',
				params: {
					page: this.teacherpage,
                    pageSize: 10,
                    teacherId: this.liveMessage.teacher.teacherAccountId,
				}
			})
			.then((res) => {
				Indicator.close();
				res = res.data;
				if (res.code == 200) {
                    res.data.data.map((value,idx) => {
                        this.teacherMsg.push(value);
                    });
				} else {
                    Toast(res.msg);
				}
			}).then(() => {
                this.teacherpage++;
            })
        },
        queryPagingBy () {
			axios({
				methods: "get",
				url: '/user/live/queryPagingBy.do',
				params: {
					page: this.queryPage,
                    pageSize: 10,
				}
			})
			.then((res) => {
                res = res.data;
                if (res.data.data.length <= 0) {
                    Toast('没有更多历史消息');
                };
				if (res.code == 200) {
                    res.data.data.reverse();
                    res.data.data.map((value,idx) => {
                        this.queryPaging.unshift(value);
                    })
				} else {
                    Toast(res.msg);
                }
                this.queryPage ++;
                this.topStatus = "";
                this.$refs.loadmore.onTopLoaded();
			})
        },
        getChatting () {
            var _this = this;
            var url = 'wss://chat.goldenqh.com/sms/getChatting.do';
            // const ws = new Websocket(url);
            this.ws = new WebSocket(url);
            this.ws.onopen = () => {
                // Web Socket 已连接上，使用 send() 方法发送数据
                var data = JSON.stringify({
                    code: 301,
                    data: {id: _this.liveMessage.teacher.teacherAccountId,}
                });
                this.ws.send(data);
            };
            this.ws.onmessage = (evt) => { 
                var d = JSON.parse(evt.data);

                if(d.code === 300 && !d.expire){
                    var obj = {
                        chatType   : d.data.chatType||2,
                        updateTime : d.data.time,
                        msg        : d.data.msg,
                        name       : d.data.name,
                        accountType:d.data.accountType,
                        order : true,
                        owner : false,
                        text : true,
                    };

                    if (obj.accountType === 2) {
                        this.queryPaging.push(obj);
                        // var height = this.$refs['query-msg-wrap'].offsetHeight;
                        return;
                    } else {
                        this.teacherMsg.push(obj);
                        this.curTeacherMsg  = obj;
                        this.showTeacherTip = true;                        
                    }
                } else if (d.code == 201) {
                    this.ws.send(JSON.stringify({code:202}));
                } else {
                    if(d.data.expire){
                           this.$router.push({
                               path: "/"
                           })
                        return false;
                    };
                    if(d.data.stopLive || (d.data.stopLive === false)){
                        if(d.data.stopLive){
                            // 非直播时间
                            // Toast('非直播时间')
                        }
                        return false;
                    } else {
                        if(d.data.isOrder){
                            
                            // _this.createOrder(d.data.name,d.data.msg);
                        } else {
                            if(d.data.slience){
                                Toast("由于您之前发布了违禁内容违反了《平台发布内容管理条例》，遭到禁言7天的处罚");
                                return false;
                            }
                        }
                    }
                }
            };
            this.ws.onclose = () => { 
                // 关闭 websocket
                console.log("连接已关闭..."); 
            };
        },
        videoTip () {
            Toast('视频功能暂未开放');
        },
        sendMsg () {
            if(!this.userInfo.userPhone){
                Toast('请先登录');
                this.$router.push({
                    path: "/",
                })
                return;
            }
            
            if (this.text){
                if (this.liveMessage.stopLive) {
                    Toast('不是直播时间，不能发言');
                    return;
                };
                var text = this.text.trim();

                if (text.length > 200) {
                    Toast('发言不能超过200文字');
                } else {
                    this.ws.send(JSON.stringify({
                        code:300,
                        data:{
                            id : this.liveMessage.teacher.teacherAccountId,
                            msg : text,
                            token1 : this.token1,
                            token2 : this.token2,
                        },
                    }));

                    this.text = "";
                }
            }
        },
    },
    filters : {
        formatTime (dateTimeStamp) {
            function add0(m){return m<10?'0'+m:m };
			var time = new Date(dateTimeStamp);
            var y = time.getFullYear();
            var m = time.getMonth()+1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
		}
    }
}
</script>

<style scoped>
    main{
        height: 100%;
    }
    .video{
        background-repeat: no-repeat !important;
        background-position: center center !important;
        background-size: cover !important;
    }
    .list{
        position: fixed;
        width: 100%;
        top: 40px;
    }
    .list>div{
        display: flex;
        justify-content: space-between;
    }
    .list>div section{
        flex: 1;
    }
    .list img{
        border-radius: 20px;
    }
    .nav span{
        flex: 1;
    }
    .nav span.red i{
        border-bottom: 2px solid #F96D46;
    }
   
    header{
        position: fixed;
        width: 100%;
        top: 0;
        left: 0;
        height: 40px;
        line-height: 40px;
        z-index: 99;
        background-color: #fff;
    }
    header em{
        vertical-align: -1px;
    }
    header div {
        width: 100%;
        display: flex;
        justify-content: space-between;
        color: #000;
    }
    .content{
        position: fixed;
        top: 238px;
        left: 0;
        right: 0;
        bottom: 56px;
        overflow-y: scroll
    }
   
    .teacher{
        background-color: #E0EAFB;
        border-radius: 12px;
        position: relative;
    }
    .user{
        background-color: #ECEDF1;
        border-radius: 12px;
        position: relative;
        color: #2E2D2D;
    }
    .box p:last-child{
        padding: 10px;
    }
    .teacher em{
        position: absolute;
        left: -16px;
        bottom: 14px;
        width: 16px;
        height: 8px;
        background-color: red;
    }
    .user span{
        position: absolute;
        right: -16px;
        bottom: 14px;
        width: 16px;
        height: 8px;
        background-color: red;
    }
    .text-wrap{
        position: fixed;
        width: 100%;
        height: 57px;
        left: 0;
        bottom: 0;
        display: flex;
    }
    .text-wrap input {
        flex: 1;
        margin-left: 20px;
        margin-right: 20px;
        height: 35px;
        line-height: 35px;
        border: 0 none;
        border-radius: 4px;
        background-color: #fff;
        margin-top: 11px;
        padding-left: 10px;
    }
    .text-wrap button{
        margin-top: 11px;
    }
    
    .slide-fade-enter-active {
		transition: all .3s ease;
	}
	.slide-fade-leave-active {
		transition: all .3s ease;
	}
	.slide-fade-enter, .slide-fade-leave-to
		/* .slide-fade-leave-active for below version 2.1.8 */ {
		transform: translateY(-300px);
    }
</style>